// pages/recharge/recharge.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    amountList: [],
    selIndex: 10,
    payTotal: 0,
    balance: 0,
    reId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initApp()
  },

  rechargeDetail: function () {
    wx.navigateTo({
      url: './list/list',
    })
  },

  initApp: function() {
    let that = this
    wx.showLoading({
      mask: true,
      title: '数据加载中',
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/customer/recharge?access_token=' + accessToken,
        success: res => {
          that.setData({
            balance: res.data.data.balance,
            amountList: res.data.data.amount
          })
          wx.hideLoading()
        }
      })
    })
  },

  /**
   * 
   */
  amountClick: function(e) {
    let total = e.currentTarget.dataset.at,
        reid = e.currentTarget.id
    this.setData({
      payTotal: total,
      selIndex: e.currentTarget.dataset.index,
      reId: reid,
    })
  },

  /**
   * 
   */
  rechargClick: function() {
    let that = this,
        payInfo
    
    if (that.data.payTotal == 0) {
      wx.showModal({
        title: '提示',
        content: '请选择充值金额',
      })

      return false
    }

    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })

    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/wxpay/recharge?access_token=' + accessToken + '&total_amount=' + that.data.payTotal,
        data: {
          recharge_amount_id: that.data.reId
        },
        success: res => {
          if(res.data.status === 1) {
            payInfo = res.data.data
            wx.requestPayment({
              timeStamp: payInfo.timeStamp,
              nonceStr: payInfo.nonceStr,
              package: payInfo.package,
              signType: payInfo.signType,
              paySign: payInfo.paySign,
              success: res => {
                wx.hideLoading()
                if (res.errMsg == 'requestPayment:ok') {
                  wx.reLaunch({
                    url: '/pages/success/success',
                  })
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.errMsg,
                  })
                }
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  icon: 'none',
                  title: '交易取消',
                })
              }
            })
          }
        }
      })
    })
  }
})